<template>
	<view>
		<top-bar>
			<template #left>
				<image src="../../static/images/login/back.png" @tap="back" style="width: 44rpx;height: 44rpx;"></image>
			</template>
			<template #center>
				<text style="font-size: 40rpx;">人工智能助手</text>
			</template>
			<template #right>
				<view>
				</view>
			</template>
		</top-bar>
		<view class="main">
			<scroll-view :scroll-into-view="scrollToView" class="chat" scroll-y="true"
				:style="{height:scrollHeight+'px'}" style="height:520px;margin-top: 50px;">
				<view class="chat-main">
					<view class="chat-ls" v-for="(item,index) in msgs" :key="item.id" :id="`msg${index}`">
						<view class="msg-m msg-left" v-if="item.isRobot">
							<image src="/static/images/cheat/machine.png" @tap="toGarllery(user._id)" class="user-img">
							</image>
							<view class="message">
								<view class="msg-text">{{item.message}}</view>
							</view>
						</view>
						<view class="msg-m msg-right" v-else>
							<image :src="userinfo.imgrul" @tap="toGarllery(MasterUserID)" class="user-img"></image>
							<view class="message" v-if="item.types==0">
								<view class="msg-text">{{item.message}}</view>
							</view>
						</view>
					</view>
				</view>
				<view class="padbt"></view>
			</scroll-view>
			<view class="submit">
				<view class="textfield " :style="{backgroundColor: generating?'#dbdbdb':'#ffffff'}">
					<textarea class="textarea" @focus="focusIpt" :disabled="generating"
						:placeholder="generating?'生成中,请稍后...':'请输入问题'" v-model="message" maxlength="300" cols="30"
						rows="10"></textarea>
					<button @tap="send" v-show="message.length>0">发送</button>
					<button style=" background: #cfcfcf;color: gray;" v-show="message.length<=0">发送</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		nextTick
	} from "vue";
	import TopBar from "../../components/top-bar/top-bar.vue"
	import {
		RuntimeServerUrl
	} from "../../commons/getRuntimeEnv.js"
	import {
		robotMessage,
		getRobotMsg
	} from "../../api/robot/robot.js"
	export default {
		data() {
			return {
				msgs: [],
				userinfo: {},
				message: "",
				anwser: "",
				scrollToView: "",
				scrollHeight: 0,
				generating: false
			}
		},
		onReady() {
			let _this = this;
			uni.getSystemInfo({ //调用uni-app接口获取屏幕高度
				success(res) { //成功回调函数
					let wHeight = res.windowHeight //windoHeight为窗口高度，主要使用的是这个
					let titleH = uni.createSelectorQuery().select(".chat"); //想要获取高度的元素名（class/id）
					titleH.boundingClientRect(data => {
						//单位是px
						_this.scrollHeight = wHeight - data.top //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
					}).exec()
				}
			})
		},
		onLoad() {
			this.userinfo = uni.getStorageSync("userInfo");
			//获取聊天数据
			this.getMsg()
			console.log(this.msgs.length, "msg lens");
		},
		methods: {
			focusIpt() {
				this.toBottom()
			},
			getMsg() {
				getRobotMsg(this.userinfo._id).then(res => {
					console.log(res.data.status, "robmsg");
					if (res.data.status == 200) {
						this.msgs = res.data.result
						console.log(this.msgs, "msgs");
						this.toBottom()
					} else {
						//失败
						console.log(res, "error");
					}
				})
			},
			async send() {
				if (this.message.trim() == "") return;
				this.msgs.push({
					"id": Math.random().toString(36).slice(2),
					"test": "1",
					"message": this.message,
					"types": "0",
					"time": "2023-12-21T12:51:14.390Z",
					"fromId": "6379ef771bcddf8551c393b1",
					"imgurl": "/user/16971213915096379ef771bcddf8551c393b15.png"
				})


				//用户发送的消息
				let msgtemp = this.message;
				this.message = ""
				this.toBottom()
				this.generating = true
				this.msgs.push({
					"id": Math.random().toString(36).slice(2),
					"test": "1",
					"message": "",
					"isRobot": "true",
					"types": "0",
					"time": "2023-12-21T12:51:14.390Z",
					"fromId": "6379ef771bcddf8551c393b1",
					"imgurl": "/user/16971213915096379ef771bcddf8551c393b15.png"
				})
				// setInterval(() => {
				// 	this.msgs[this.msgs.length - 1].message += 1
				// }, 1000)
				//将聊天数据处理成 需要的格式
				let histroy = []
				this.msgs.slice(-10).map((item, index) => {
					console.log(item, index, "index");
					if (item.message != '') {
						if (item.isRobot) {
							histroy.push({
								role: "assistant",
								content: item.message
							})
						} else {
							histroy.push({
								role: "user",
								content: item.message
							})

						}
					}
				})
				console.log(histroy, "history");
				this.gen([
					//旧消息
					...histroy,
					//最新一条消息 
					{
						role: 'user',
						content: msgtemp,
					},
				], this.userinfo._id)
				this.toBottom()
			},
			gen(question, userid) {
				const url = new URL("/gen", RuntimeServerUrl)
				url.searchParams.set("prompt", JSON.stringify(question))
				url.searchParams.set("userId", userid)
				this.eventSource = new EventSource(url)
				this.eventSource.addEventListener('message', (event) => {
					console.log("message", event);
					console.log("message", event.data);
					if (event.data != "DONE") {
						this.msgs[this.msgs.length - 1].message += event.data
						this.toBottom()
					} else {
						this.generating = false
						this.eventSource.close()
					}
				});

				// 监听 error 事件，处理连接错误
				this.eventSource.addEventListener('error', function(error) {
					console.error('EventSource encountered an error:', error);
				});
				this.eventSource.addEventListener('close', function() {
					console.log('close');
				});
			},
			back() {
				uni.navigateBack()
			},
			toBottom(e) {
				// 这个值变化了才会触发动画
				this.scrollToView = ''
				this.$nextTick(function() {
					// 没有效果
					this.scrollToView = `msg${(this.msgs.length-1)}`
					// console.log(this.scrollToView);
				}, 100)
			},
			// toButtom() {
			// 	uni.createSelectorQuery().select('.padbt').boundingClientRect(rect => {
			// 		uni.pageScrollTo({
			// 			scrollTop: rect.top,
			// 			duration: 300
			// 		})
			// 	}).exec()
			// }
		}
	}
</script>


<style lang="scss">
	.content {
		padding-top: var(--status-bar-height);
		height: calc(100vh- 88rpx + var(--status-bar-height));
		// height: 100vh;
		overflow: hidden;
	}

	.main {
		// margin-top: var(--status-bar-height);
		// margin-top: calc(88rpx + var(--status-bar-height));
		height: 85vh;

		.chat {

			// height: 1350rpx; 
			.chat-main {
				padding: 0rpx 32rpx 0rpx 32rpx;
				display: flex;
				flex-direction: column;
				margin-top: 40px;
			}

			// 占位
			.padbt {
				height: 300rpx;
				width: 100%;
			}

			.chat-ls {
				.chat-time {
					text-align: center;
					font-size: 24rpx;
					color: rgba(39, 40, 50, 0.30);
					padding: 20rpx 0;
				}

				//左右公用的数据
				.msg-m {
					display: flex;
					padding: 20rpx 0;

					.user-img {
						flex: none;
						width: 80rpx;
						height: 80rpx;
						border-radius: 20rpx;
					}

					.message {
						max-width: 480rpx;
						/*这两行代码可以解决大部分场景下的换行问题*/
						word-break: break-all;
						word-wrap: break-word;
						/*但在有些场景中，还需要加上下面这行代码*/
						white-space: normal;

						.msg-text {
							font-size: 32rpx;
							color: $uni-text-color;
							line-height: 44rpx;
							min-height: 44rpx;
							padding: 18rpx 24rpx;

							image {
								display: inline-block;
								line-height: 16rpx;
								width: 40rpx;
								height: 40rpx;
							}
						}

						.msg-img {
							max-width: 400rpx;
							border-radius: 20rpx;
						}
					}

					.voice {
						image {
							padding-top: 10rpx;
						}

						// .msg-text{
						// 	float: right;
						// 	width: 100rpx;
						// }
						.tip_left {
							// animation: paly 0.5s infinite alternate;
							float: right;
							line-height: 28rpx;
						}

						.tip_right {
							float: left;
							line-height: 28rpx;
						}

					}

					.mapMsg {
						.msg-text {
							max-width: 440rpx;
							width: 400rpx;
							background-color: #fff;
							padding: 0;

							.mapMsg-location {
								padding: 10rpx 20rpx 0rpx 20rpx;
								font-size: 36rpx;
								letter-spacing: 4rpx;
								// width: 95%;
								height: 100%;
							}

							.mapMsg-address {
								padding: 0rpx 20rpx 10rpx 20rpx;
								font-size: 26rpx;
								color: #a2a2a2;
								display: -webkit-box;
								-webkit-box-orient: vertical;
								-webkit-line-clamp: 1;
								overflow: hidden;
							}

							.mapMsg-map {
								// border: 1px solid;
								height: 250rpx;
								width: 100%;

								image {
									border-bottom-left-radius: 16rpx;
									border-bottom-right-radius: 16rpx;
								}
							}
						}
					}
				}

				.msg-left {
					flex-direction: row;

					.msg-text {
						margin-left: 16rpx;
						background-color: #d0d0d0;
						border-radius: 0 20rpx 20rpx 20rpx;
					}

					.msg-img {
						margin-left: 16rpx;
					}
				}

				.msg-right {
					flex-direction: row-reverse;

					.msg-text {
						margin-right: 16rpx;
						background-color: #FFf260;
						;
						border-radius: 20rpx 0rpx 20rpx 20rpx;
					}

					.msg-img {
						margin-right: 16rpx;
					}
				}
			}
		}
	}

	.isplay {
		animation: paly 0.2s infinite alternate;
	}

	@keyframes paly {
		from {
			transform: scale(0.9, 0.9);
		}

		to {
			transform: scale(1.2, 1.2);
		}
	}

	.textfield {

		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
		box-sizing: border-box;
		padding-bottom: 40px;
		border: 4px solid #dbdbdb;
		position: fixed;
		bottom: 0;
		background: white;
		width: 100%;

		textarea {
			width: 98%;
			height: 100px;
			box-sizing: border-box;
			padding: 8rpx;
			border-radius: 0 6px;
			margin: 0 1px;
			font-size: 34rpx;
			// border-top: 1px solid gray;
			width: 100%;
		}

		button {
			position: absolute;
			bottom: 0;
			right: 0;
			margin: 10rpx;
			font-size: 26rpx;
			height: 30px;
			line-height: 28px;
			width: 66px;
			text-align: center;
			border: 1px solid skyblue;
			background-color: greenyellow;
			border-radius: 5px;

		}
	}
</style>